#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name:     main.py
# Author:   xiooli <xioooli[at]yahoo.com.cn>
# Site:     http://joolix.com
# Licence:  GPLv3
# Version:  101217

from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import types
from plugins import *

# you can add more handlers here to power your bot
# a handler is a class with at least a handler.handle(*words)
# method to handle the messages passed by the users
Handlers = {
        ('-t', '--trans', '--translate'): translate(),
        ('-i', '--input'): mypinyin(),
        'default': chat()
        }

def get_handler(option, handlers = Handlers):
    for k, v in handlers.items():
        if type(k) == types.TupleType and (option in k):
            return (True, v)
    return (False, handlers['default'])

class XMPPHandler(webapp.RequestHandler):
    def post(self):
        message = xmpp.Message(self.request.POST)
        msg = message.body.encode("utf8")
        argv = [ i for i in msg.split(' ') if i ] + ['', '']
        has_opt = False
        has_opt, handler = get_handler(argv[0])
        response = None
        if handler:
            response = handler.handle(has_opt and ' '.join(argv[1:]) or ' '.join(argv))
        if response:
            message.reply(response)

application = webapp.WSGIApplication([('/_ah/xmpp/message/chat/', XMPPHandler)], debug=True)

if __name__ == "__main__":
    run_wsgi_app(application)
